package icu.sehnen.es.controller;

import icu.sehnen.common.result.CommonResult;
import icu.sehnen.es.entity.ESUser;
import icu.sehnen.es.entity.User;
import icu.sehnen.es.service.ESUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huangqing
 * @version 1.0
 * @date 2021/5/7 16:44
 */
@RestController
public class PermissionController {

    @Autowired
    private ESUserService esUserService;
//高亮查询
  @GetMapping("/find")
    public Object  searchHits(String keyword,Integer pageNum,Integer pageSize){
        SearchHits searchHits = esUserService.searchHit(keyword, pageNum, pageSize);
        List<SearchHit> hitList = searchHits.getSearchHits();   //得到查询结果
        ArrayList<ESUser> fields = new ArrayList<>();
        System.out.println(hitList);
        for (SearchHit searchHit : hitList) {
          ESUser esUser =(ESUser)searchHit.getContent();
          esUser.setUsername(searchHit.getHighlightField("username").toString());
          fields.add(esUser);
        }
        // todo 这里作业就是将 list里面的内容转换成  List<EsPermission> 返回给前端
        return fields;
    }
//保存数据
    @PostMapping("/save")
    public CommonResult save(User user){
       User user1=esUserService.save(user);
       if (user1==null){
           return CommonResult.failed();
       }
       return CommonResult.success();
    }
//查询所有
    @GetMapping("/findAll")
    public CommonResult findAll(Integer pageNum,Integer pageSize){
        Page<ESUser> userList=esUserService.findAll(pageNum,pageSize);
        return CommonResult.success(userList);
    }
}